﻿/// <reference path="json2.js" />

function ajaxIntoCar(id) {
    $.ajax({
        url: "/ajax/ajaxproductinfo.ashx",
        type: "get",
        dataType: "text",
        cache: false,
        data: { methodName: "IntoShoppingCart", pid: id, r: Math.random() },
        success: function (r) {
            var res = eval('(' + r + ')');
            if (res.state != -1) {
                if (res.state == 1) {
                    updateQuantity(id, parseInt(queryCntById(id)) + 1);
                    window.location.href = "order.aspx";
                }
                else {
                    intoCar(res.Id, 1, res.ProductName, res.ShoppingCartThumbUrl, res.Price, res.CategoryId, res.ProductEName, res.ProductStyle);
                    window.location.href = "order.aspx";
                }
            } else {
                alert("没有找到当前产品!");
            }
        }, error: function (xhr) {
            alert(xhr.responseText);
        }
    })
}

function delArr(ar, n) {
    if (n < 0)
        return ar;
    else
        return ar.slice(0, n).concat(ar.slice(n + 1, ar.length));
}

function intoCar(proid, quantity, proname, imgurl, _price, _cateid, _ename, _style) {

    if (proid != "" && proname != "") {
        var ProIDList = cookie.Get("carList");
        if (ProIDList != null && ProIDList != "" && ProIDList != "null") {

            ProIDList += "&" + proid + "=" + proid + "|" + quantity + "|" + _price + "|" + _cateid;
            cookie.Set("carList", ProIDList, 2, "/");
            TotalPro = cookie.Get("TotalPro");
            TotalPro++; //总数+1
            cookie.Set("TotalPro", TotalPro, 2, "/");

            totalCates = cookie.Get("totalCates");
            if (!singleCateisExist(totalCates, _cateid)) {
                totalCates = totalCates + "_" + _cateid
            }
            cookie.Set("totalCates", totalCates, 2, "/");

        }
        else {
            ProIDList = proid + "=" + proid + "|" + quantity + "|" + _price + "|" + _cateid;
            cookie.Set("carList", ProIDList, 2, "/");
            cookie.Set("TotalPro", 1, 2, "/");
            cookie.Set("totalCates", _cateid, 2, "/");
        }
    }

}
function reloadcar() {
    var t = cookie.Get("TotalPro");
    if (t != "" && t != "null")
        document.getElementById("cart_num").innerText = "(" + cookie.Get("TotalPro") + ")";
    else
        document.getElementById("cart_num").innerText = "(0)";
}

function hasOne(pid) {
    ProIDList = cookie.Get("carList");
    if (ProIDList.lastIndexOf("&") != -1) {
        var arr = ProIDList.split("&");

        for (i = 0; i < arr.length; i++) {
            //alert(arr.indexOf("="));
            if (arr[i].substr(0, arr[i].indexOf("=")) == pid) {
                return false;
            }
        }
    }
    else if (ProIDList != "null" && ProIDList != "") {
        if (ProIDList.substr(0, ProIDList.indexOf("=")) == pid)
            return false;
    }
    return true;
}
function reMoveOne(proid) {

    if (!hasOne(proid)) {
        if (ProIDList.lastIndexOf("&") != -1) {
            var arr = ProIDList.split("&");
            for (i = 0; i < arr.length; i++) {
                if (arr[i].substr(0, arr[i].indexOf("=")) == proid) {

                    var arr2 = delArr(arr, i);
                    var tempStr = arr2.join("&");

                    cookie.Set("carList", tempStr, 2, "/");
                    var t = cookie.Get("TotalPro");
                    cookie.Set("TotalPro", t - 1, 2, "/");
                    return;
                }
            }
        }
        else {
            cookie.Set("carList", null);
            var t = cookie.Get("TotalPro");
            cookie.Set("TotalPro", 0, 2, "/");


            totalCates = cookie.Get("totalCates");
        }
    }

}
function updateQuantity(proid, quantity) {
    ProIDList = cookie.Get("carList");
    if (ProIDList.lastIndexOf("&") != -1) {
        var arr = ProIDList.split("&");
        var sub = getSubPlace(ProIDList, proid);

        var arr2 = arr[sub].split("|");
        arr2[1] = quantity;
        var tempStr = arr2.join("|");
        arr[sub] = tempStr;

        var newProList = arr.join("&");
        cookie.Set("carList", newProList, 2, "/");
    }
    else {
        var arr = ProIDList.split("|");
        arr[1] = quantity;
        var newProList = arr.join("|");
        cookie.Set("carList", newProList, 2, "/");
    }

    if (queryCntById(proid) > 0) {
        $("#ico_" + proid).show();
    } else {
        $("#ico_" + proid).hide();
    }
}
function turnProductQuantity(proid, action) {

    ProIDList = cookie.Get("carList");
    if (ProIDList.lastIndexOf("&") != -1) {
        var arr = ProIDList.split("&");

        var sub = getSubPlace(ProIDList, proid);
        var arr2 = arr[sub].split("|");

        if (action == "increment") {
            arr2[1] = parseInt(arr2[1]) + 1;
        } else {
            arr2[1] = parseInt(arr2[1]) - 1;
            if (arr2[1] <= 0) {
                arr2[1] = 0;
                reMoveOne(proid);
            }
        }

        $("#pid_" + proid + "_cnt").val(arr2[1]);

        var tempStr = arr2.join("|");
        arr[sub] = tempStr;

        var newProList = arr.join("&");

        cookie.Set("carList", newProList, 2, "/");

    }
    else {

        var arr = ProIDList.split("|");

        if (action == "increment") {
            arr[1] = parseInt(arr[1]) + 1;
            if ((parseInt(arr[1]) + 1) > 0) {
                $("#ico_" + proid).show();
            }
        }
        else {
            arr[1] = parseInt(arr[1]) - 1;
            if (arr[1] <= 0) {
                arr[1] = 0;
                reMoveOne(proid);

                $("#ico_" + proid).hide();
            }
        }
        $("#pid_" + proid + "_cnt").val(arr[1]);

        var newProList = arr.join("|");
        cookie.Set("carList", newProList, 2, "/");

    }

    if (queryCntById(proid) > 0) {
        $("#ico_" + proid).show();
    } else {
        $("#ico_" + proid).hide();
    }

    calanderOrderAmount();
}


function InitShoppingCart() {


    $.ajax({
        url: "ajax/ajaxproductinfo.ashx",
        dataType: "json",
        cache: false,
        data: { "methodName": "QueryProductsByCid" },
        type: "get",
        success: function (cartsRes) {


            var aa = cookie.Get("carList");
            var container = ' <table width="770" cellspacing="0">';
            var items = "";
            var content = "";
            var body = "";
            var cates;
            if (cookie.Get("totalCates") != "null" && cookie.Get("totalCates") != null && cookie.Get("totalCates") != "") {
                cates = cookie.Get("totalCates").split("_");
                $.each(cartsRes, function (i, it) {

                    var v = matchStyle(it.cid);
                    var styleName = "";
                    var cateName = "";
                    if (v.indexOf('&') > -1) {
                        vv = v.split('&');
                        styleName = vv[0];
                        cateName = vv[1];
                    }
                    if (it.values.length > 0) {
                        content += '<tr class=' + styleName + '> <td class="style4"> ' + cateName + ' </td><td align="center"> 商品图 </td> <td align="center"> 规格 </td> <td align="center"> 价格</td><td align="center"> 数量</td><td align="center" style="width:40px;"></td></tr>';
                    }

                    $.each(it.values, function (ii, item) {

                        if (it.values.length > 0) {
                            content += " <tr><td class=\"style4\"><a href='detail.aspx?id=" + item.Id + "' style='text-decoration:none;color:black;'>" + decodeURIComponent(item.ProductName) + " / " + decodeURIComponent(item.ProductEName) + "</a> </td> ";
                            content += "<td align=\"center\"> <img width=\"80px\" height=\"80px\"  src=" + decodeURIComponent(item.ShoppingCartThumbUrl) + "></td>";
                            content += "<td align=\"center\"> " + decodeURIComponent(item.ProductStyle) + "</td>";
                            content += "<td align=\"center\"> " + (item.Price) + "</td>";
                            content += "<td align=\"center\"> <a class='dotIco' id='add_" + (item.Id) + "' href='javascript:void(0);' onclick='turnProductQuantity(\"" + item.Id + "\",\"increment\")'><img src='/images/bag_open.gif' border='0'></a> <input class='pntQuantity' id='pid_" + (item.Id) + "_cnt' type='text' value=" + (item.quantity) + " onblur='quickModifyProCnt(" + item.Id + ")'></input><a class='dotIco' id='del_" + item.Id + "' href='javascript:void(0);' onclick='turnProductQuantity(\"" + item.Id + "\",\"decrement\")'><img src='/images/bag_close.gif' border='0'></a></td>";

                            var ico = "";
                            if (item.quantity != 0) {
                                ico = "<b id='ico_" + item.Id + "' class='ico-succ'></b>";
                            } else {
                                ico = "<b id='ico_" + item.Id + "' class='ico-succ' style='display:none;'></b>";
                            }
                            content += "<td align=\"center\">" + ico + "</td>";
                            content += " </tr>";
                        }
                    })
                })


                body += content;
                container += body + '</table>';
            }
            else {
                container += "<tr style='cospan=6'><td></td></tr></table>";
            }
            $("#cart").html(container);
            calanderOrderAmount();
        }
    })


    //    var aa = cookie.Get("carList");



    //    var container = ' <table width="770" cellspacing="0">';
    //    var items = "";
    //    var content;
    //    var body = "";
    //    var cates;

    //    if (cookie.Get("totalCates") != "null" && cookie.Get("totalCates") != null && cookie.Get("totalCates") != "") {
    //        cates = cookie.Get("totalCates").split("_");

    //        for (var i = 0; i < cates.length; i++) {

    //            //分类有可能有匹配不到的结果
    //            if (getItemByCidPlace(aa, cates[i]) == "[]" || getItemByCidPlace(aa, cates[i]) == "") {
    //                continue;
    //            }

    //            items = $.evalJSON(getItemByCidPlace(aa, cates[i]));

    //            var v = matchStyle(cates[i]);
    //            var styleName = "";
    //            var cateName = "";
    //            if (v.indexOf('&') > -1) {
    //                vv = v.split('&');
    //                styleName = vv[0];
    //                cateName = vv[1];
    //            }

    //            content = '<tr class=' + styleName + '> <td class="style4"> ' + cateName + ' </td><td align="center"> 商品图 </td> <td align="center"> 规格 </td> <td align="center"> 价格</td><td align="center"> 数量</td><td align="center" style="width:40px;"></td></tr>';
    //            $.each(items, function (i, item) {
    //                content += " <tr><td class=\"style4\"><a href='detail.aspx?id=" + item.id + "' style='text-decoration:none;color:black;'>" + decodeURIComponent(item.name) + " / " + decodeURIComponent(item.ename) + "</a> </td> ";
    //                content += "<td align=\"center\"> <img width=\"80px\" height=\"80px\"  src=" + decodeURIComponent(item.imgurl) + "></td>";
    //                content += "<td align=\"center\"> " + decodeURIComponent(item.specification) + "</td>";
    //                content += "<td align=\"center\"> " + (item.pirce) + "</td>";
    //                content += "<td align=\"center\"> <a class='dotIco' id='add_" + (item.id) + "' href='javascript:void(0);' onclick='turnProductQuantity(\"" + item.id + "\",\"increment\")'><img src='/images/bag_open.gif' border='0'></a> <input class='pntQuantity' id='pid_" + (item.id) + "_cnt' type='text' value=" + (item.quantity) + " onblur='quickModifyProCnt(" + item.id + ")'></input><a class='dotIco' id='del_" + item.id + "' href='javascript:void(0);' onclick='turnProductQuantity(\"" + item.id + "\",\"decrement\")'><img src='/images/bag_close.gif' border='0'></a></td>";

    //                var ico = "";
    //                if (item.quantity != 0) {
    //                    ico = "<b id='ico_" + item.id + "' class='ico-succ'></b>";
    //                } else {
    //                    ico = "<b id='ico_" + item.id + "' class='ico-succ' style='display:none;'></b>";
    //                }
    //                content += "<td align=\"center\">" + ico + "</td>";
    //                content += " </tr>";
    //            })
    //            body += content;
    //        }
    //        container += body + '</table>';
    //    } else {
    //        container += "<tr style='cospan=6'><td></td></tr></table>";
    //    }
    //    $("#cart").html(container);
    //    calanderOrderAmount();
}
function getSubPlace(list, proid) {
    var arr = list.split("&");
    for (i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, arr[i].indexOf("=")) == proid) {
            return i;
        }
    }
}
function getItemByCidPlace(list, cateid) {


    var items = [];
    if (list.indexOf("&") != -1) {
        var arr = list.split("&");
        for (i = 0; i < arr.length; i++) {

            if (arr[i].substr(arr[i].lastIndexOf("|") + 1, arr[i].length) == cateid) {

                var item = arr[i].split("|");
                var id = item[0].split("=")[0]

                $.ajax({
                    url: "ajax/ajaxproductinfo.ashx?methodName=QueryProductById",
                    dataType: "json",
                    cache: false,
                    async: false,
                    data: { pid: id, r: Math.random() },
                    type: "get",
                    success: function (product) {
                        items.push("{\"id\":\"" + id + "\",\"name\":\"" + product.ProductName + "\",\"imgurl\":\"" + product.ShoppingCartThumbUrl + "\",\"pirce\":\"" + product.Price + "\",\"cateid\":\"" + cateid + "\",\"quantity\":\"" + item[1] + "\",\"specification\":\"" + product.ProductStyle + "\",\"ename\":\"" + product.ProductEName + "\"}");
                    }
                })
            }
        }
    }
    else {
        if (list.substr(list.lastIndexOf("|") + 1, list.length) == cateid) {
            var item = list.split("|");
            var id = item[0].split("=")[0];
            $.ajax({
                url: "ajax/ajaxproductinfo.ashx?methodName=QueryProductById",
                dataType: "json",
                cache: false,
                async: false,
                data: { pid: id, r: Math.random() },
                type: "get",
                success: function (product) {
                    items.push("{\"id\":\"" + id + "\",\"name\":\"" + product.ProductName + "\",\"imgurl\":\"" + product.ShoppingCartThumbUrl + "\",\"pirce\":\"" + product.Price + "\",\"cateid\":\"" + cateid + "\",\"quantity\":\"" + item[1] + "\",\"specification\":\"" + product.ProductStyle + "\",\"ename\":\"" + product.ProductEName + "\"}");
                }
            })
        }
    }

    return "[" + items.join(',') + "]";
}





function singleCateisExist(catelist, cid) {
    if (catelist.indexOf("_") != -1) {
        var items = catelist.split("_");
        for (var i = 0; i < items.length; i++) {
            if (items[i] == cid) {
                return true;
            }
        }
    } else {
        if (catelist == cid) {
            return true;
        }
    }
    return false;
}
function calanderOrderAmount() {


    //   proid + "=" + proid + "|" + quantity + "|" + _price + "|" + _cateid;
    var prots = cookie.Get("carList");
    var total = 0;
    var item;
    if (prots != null && prots != "" && prots != "null") {
        if (prots.indexOf("&") != -1) {
            var arr = prots.split("&");
            for (var i = 0; i < arr.length; i++) {
                item = arr[i].split("|");

                total += parseInt(item[1]) * item[2];
            }
        } else {
            item = prots.split("|");
            total = parseInt(item[1]) * item[2];
        }

        if (cookie.Get("Amount") != null) {
            var amount = cookie.Get("Amount");
            amount = total;
            cookie.Set("Amount", amount, 2, "/");
        }
        else {
            cookie.Set("Amount", total, 2, "/");
        }
    }


    return $("#amount").html("<a style='color:red;'>￥：" + total + "</a>");
}

function matchStyle(i) {
    var catesStyles = new Array("style_y", "style_p", "style_g", "style_b");
    var catesCateNames = new Array("鲜榨果蔬汁 / Juice", "甜品&小食 / Dessert", "活力代餐饮 / Nutritional meal ", "健康主题计划 / Health plan");
    return catesStyles[i - 1] + "&" + catesCateNames[i - 1];
}

function quickModifyProCnt(id) {
    var itemObj = $("#pid_" + id + "_cnt");
    var oriCnt = queryCntById(id)
    var reg = new RegExp("^[0-9]*$");

    if (itemObj.val() == 0)//默认第一次初始化
    {
        itemObj.val(0);
        updateQuantity(id, itemObj.val());

    }
    else {
        if (!reg.test(itemObj.val())) {

            itemObj.val(oriCnt);
        }
        else {
            if (itemObj.val() >= 500) {
                alert("当前商品购买数量上限不能大于500哦!");
                itemObj.val(oriCnt);

            } else {
                updateQuantity(id, itemObj.val());
            }
        }
    }


    calanderOrderAmount();
}

function queryCntById(id) {
    var prots = cookie.Get("carList");
    if (prots != null && prots != "" && prots != "null") {
        if (prots.indexOf("&") > -1) {
            var cts = prots.split('&');
            var index = getSubPlace(prots, id);
            return cts[index].split('|')[1];
        }
        else {
            return prots.split('|')[1];
        }
    }
}


var cookie = {
    Get: function (n) {
        var re = new RegExp(n + '=([^;]*);?', 'gi');
        var r = re.exec(document.cookie) || [];
        return (r.length > 1 ? r[1] : null)
    },
    Set: function (n, v, e, p, d, s) {
        var t = new Date;
        if (e) {
            // 8.64e7 一天  3.6e6 一小时
            t.setTime(t.getTime() + (e * 8.64e7));
        }
        document.cookie = n + '=' + v + '; ' + (!e ? '' : '; expires=' + t.toUTCString()) + (!p ? '' : '; path=' + p) + (!d ? '' : '; domain=' + d) + (!s ? '' : '; secure')  // Set cookie
    },
    Del: function (n, p, d) {
        var t = cookie.Get(n);
        document.cookie = n + '=' + (!p ? '' : '; path=' + p) + (!d ? '' : '; domain=' + d) + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
        return t
    }
}